<?php
/*
 * @Author       : ZengHao
 * @Date         : 2023-12-23 19:12:01
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-02-01 23:11:45
 * @FilePath     : /inc/functions/el-optimize.php
 * @Description  : 
 * Copyright 2023 www.exehub.com, All Rights Reserved. 
 * 2023-12-23 19:12:01
 */

//WordPress 5.0+移除 block-library CSS
add_action('wp_enqueue_scripts', 'fanly_remove_block_library_css', 100);
function fanly_remove_block_library_css()
{
    wp_dequeue_style('wp-block-library');
}

// 这是总开关，打开后才去判断下面的子项目是否需要进行优化
if (_opz('el_clean_dash')) {
    add_action('admin_bar_menu', 'el_clean_edit_toolbar', 999);
    add_action('wp_dashboard_setup', 'el_remove_dashboard_widgets');
}

// 去除WordPress顶部工具栏无用项目 - https://www.el_remove.net/72.html
function el_clean_edit_toolbar($wp_toolbar)
{
    if (_opz('el_clean_toolbar')) {
        foreach (_opz('el_clean_toolbar_items') as $item) {
            $wp_toolbar->remove_node($item);
        }
    }
}

// 去除WordPress移除仪表盘无用模块清理 - https://www.el_remove.net/72.html
function el_remove_dashboard_widgets()
{
    if (_opz('el_remove_dashboard_widgets')) {
        global $wp_meta_boxes;
        foreach (_opz('el_remove_dashboard_widgets_items') as $item) {
            if (
                $item == 'dashboard_quick_press' || $item == 'dashboard_recent_drafts'
                || $item == 'dashboard_primary' || $item == 'dashboard_secondary'
            ) {
                unset($wp_meta_boxes['dashboard']['side']['core'][$item]);
            } elseif (
                $item == 'dashboard_incoming_links' || $item == 'dashboard_plugins'
                || $item == 'dashboard_recent_comments' || $item == 'dashboard_right_now'
                || $item == 'dashboard_activity'
            ) {
                unset($wp_meta_boxes['dashboard']['normal']['core'][$item]);
            } elseif ($item == 'dashboard_site_health') {
                remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
            } elseif ($item == 'welcome_panel') {
                remove_action('welcome_panel', 'wp_welcome_panel');
            } elseif ($item == 'dashboard_php_nag') {
                unset($wp_meta_boxes['dashboard']['normal']['high']['dashboard_php_nag']);
            }
        }
    }
}

//移除后台仪表盘菜单：帮助
if (_opz('el_clean_help')) {
    function el_clean_help()
    {
        get_current_screen()->remove_help_tabs();
    }
    add_action('admin_head', 'el_clean_help');
}

//非关闭顶部admin_bar
if (_opz('hide_admin_bar', true) || !is_super_admin()) {
    add_filter('show_admin_bar', '__return_false');
}

// 删除WordPress Emoji 表情
if (_opz('remove_emoji', true)) {
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('admin_print_styles', 'print_emoji_styles');
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_filter('the_content_feed', 'wp_staticize_emoji');
    remove_filter('comment_text_rss', 'wp_staticize_emoji');
    remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
}


//删除google字体
if (_opz('remove_open_sans', true)) {
    function remove_open_sans()
    {
        wp_deregister_style('open-sans');
        wp_register_style('open-sans', false);
        wp_enqueue_style('open-sans', '');
    }
    add_action('init', 'remove_open_sans');
}

// 删除多于头部代码
if (_opz('remove_other_meta', true)) {
    function remove_other_meta()
    {
        remove_action('wp_head', 'feed_links_extra', 3); // 移除feed
        remove_action('wp_head', 'feed_links', 2); // 移除feed
        remove_action('wp_head', 'rsd_link'); // 移除离线编辑器开放接口
        remove_action('wp_head', 'wlwmanifest_link'); // 移除离线编辑器开放接口
        remove_action('wp_head', 'index_rel_link'); // 移除Index link 去除本页唯一链接信息
        remove_action('wp_head', 'parent_post_rel_link', 10, 0); // 移除Prev link 清除前后文信息
        remove_action('wp_head', 'start_post_rel_link', 10, 0); // 移除Start link 清除前后文信息
        remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // 移除与当前帖子相邻的帖子的关系链接。
        remove_action('wp_head', 'wp_generator'); // 移除WordPress版本信息
        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); // 移除与当前帖子相邻的帖子的关系链接
        remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
        remove_action('wp_head', 'wp_oembed_add_discovery_links', 10, 1);
        remove_action('wp_head', 'rel_canonical', 10, 0);
        remove_action('wp_head', 'wp_resource_hints', 2); //移除dns-prefetch
    }
    add_action('after_setup_theme', 'remove_other_meta'); //清除wp_head带入的meta标签
}

// 禁用更新
if (_opz('disable_wp_update', true)) {
    remove_action('admin_init', '_maybe_update_core'); // 禁止 WordPress 检查更新
    remove_action('admin_init', '_maybe_update_plugins'); // 禁止 WordPress 更新插件
    remove_action('admin_init', '_maybe_update_themes'); // 禁止 WordPress 更新主题

    //禁用 WordPress 插件自动更新 
    add_filter('auto_update_plugin', '__return_false');
    //禁用 WordPress 主题自动更新 
    add_filter('auto_update_theme', '__return_false');

    add_filter('automatic_updater_disabled', '__return_true');
    remove_action('init', 'wp_schedule_update_checks');
    remove_action('wp_version_check', 'wp_version_check');
    remove_action('wp_update_plugins', 'wp_update_plugins');
    remove_action('wp_update_themes', 'wp_update_themes');
    add_filter('auto_update_core', '__return_false');
    add_filter('allow_major_auto_core_updates', '__return_false');
    add_filter('allow_dev_auto_core_updates', '__return_false');
    add_filter('allow_minor_auto_core_updates', '__return_false');
    add_filter('allow_major_auto_core_updates', '__return_false');
}

//禁用古腾堡
if (_opz('disable_gtb_editor')) {
    add_filter('use_block_editor_for_post', '__return_false');
}

//wp5.8禁用古腾堡小工具
// 禁止块编辑器管理Gutenberg插件中的小部件。
add_filter('gutenberg_use_widgets_block_editor', '__return_false');
// 禁止块编辑器管理小部件。
add_filter('use_widgets_block_editor', '__return_false');

//禁用autoembed
if (_opz('disable_auto_emded', true)) {
    remove_filter('the_content', [$GLOBALS['wp_embed'], 'autoembed'], 8);
    remove_filter('widget_text_content', [$GLOBALS['wp_embed'], 'autoembed'], 8);
    remove_filter('widget_block_content', [$GLOBALS['wp_embed'], 'autoembed'], 8);
    remove_action('edit_form_advanced', [$GLOBALS['wp_embed'], 'maybe_run_ajax_cache']);
    remove_action('edit_page_form', [$GLOBALS['wp_embed'], 'maybe_run_ajax_cache']);
}

if (_opz('disable_auto_emded', true)) {
    function el_wp_add_inline_script_disabled_autoembed()
    {
        $scripts = "jQuery(function($){
                        wp.domReady(function (){
                            wp.blocks.unregisterBlockType('core/embed');
                        });
                    });";
        wp_add_inline_script('jquery', $scripts);
    }

    add_action('enqueue_block_editor_assets', 'el_wp_add_inline_script_disabled_autoembed');
}

//隐藏多余的用户设置项目
function el_user_profile_css($user)
{

    $html = '<style>
    .user-first-name-wrap,
    .user-last-name-wrap,
    .user-admin-bar-front-wrap,
    .user-comment-shortcuts-wrap,
    .user-admin-color-wrap,
    .user-syntax-highlighting-wrap,
    .user-rich-editing-wrap,
    .user-profile-picture .description,
    .user-language-wrap
     {
        display: none
    }
    </style>';
    echo $html;
}
if (_opz('clean_user_setting', true)) {
    add_action('show_user_profile', 'el_user_profile_css');
    add_action('edit_user_profile', 'el_user_profile_css');
}

// 移除文章头部feed
if (_opz('remove_feed')) {
    function disable_all_feeds()
    {
        wp_die('本站不提供feed');
    }
    add_action('do_feed', 'disable_all_feeds', 1);
    add_action('do_feed_rdf', 'disable_all_feeds', 1);
    add_action('do_feed_rss', 'disable_all_feeds', 1);
    add_action('do_feed_rss2', 'disable_all_feeds', 1);
    add_action('do_feed_atom', 'disable_all_feeds', 1);
}

// 移除Dashicons
if (_opz('remove_dashicons') && !is_admin()) {
    function wpdocs_dequeue_dashicon()
    {
        if (current_user_can('update_core')) {
            return;
        }
        wp_deregister_style('dashicons');
    }
    add_action('wp_enqueue_scripts', 'wpdocs_dequeue_dashicon');
}

// 移除谷歌地图API
if (_opz('remove_googlemap')) {
    function disable_google_map_api($load_google_map_api)
    {
        $load_google_map_api = false;
        return $load_google_map_api;
    }
    $plugins = get_option('active_plugins');
    $required_plugin = 'auto-location-pro/auto-location.php';
    if (in_array($required_plugin, $plugins)) {
        add_filter('avf_load_google_map_api', 'disable_google_map_api', 10, 1);
    }
    add_filter('avf_load_google_map_api', '__return_false');
}

// 移除WordPress自带联系表单
if (_opz('remove_contact_form')) {
    add_filter('wpcf7_load_js', '__return_false');
    add_filter('wpcf7_load_css', '__return_false');
}

// 移除WordPress自带联系表单
if (_opz('remove_translations_api')) {
    add_filter('translations_api', '__return_true');
}

// 屏蔽 Trackbacks/Pingback
if (_opz('remove_pingback')) {
    //彻底关闭 pingback
    add_filter('xmlrpc_methods', function ($methods) {
        $methods['pingback.ping'] = '__return_false';
        $methods['pingback.extensions.getPingbacks'] = '__return_false';
        return $methods;
    });

    //禁用 pingbacks, enclosures, trackbacks
    remove_action('do_pings', 'do_all_pings', 10);

    //去掉 _encloseme 和 do_ping 操作。
    remove_action('publish_post', '_publish_post_hook', 5);
}

// 关闭XML-RPC接口
if (_opz('remove_xmlrpc')) {
    add_filter('xmlrpc_enabled', '__return_false');
    add_filter('xmlrpc_methods', '__return_empty_array');
}

// 分类链接删除 'category'
if (_opz('el_remove_cat_url') && !function_exists('no_category_base_refresh_rules')) {
    register_activation_hook(__FILE__, 'no_category_base_refresh_rules');
    add_action('created_category', 'no_category_base_refresh_rules');
    add_action('edited_category', 'no_category_base_refresh_rules');
    add_action('delete_category', 'no_category_base_refresh_rules');
    function no_category_base_refresh_rules()
    {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }

    register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
    function no_category_base_deactivate()
    {
        remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
        // We don't want to insert our custom rules again
        no_category_base_refresh_rules();
    }

    // Remove category base
    add_action('init', 'no_category_base_permastruct');
    function no_category_base_permastruct()
    {
        global $wp_rewrite, $wp_version;
        if (version_compare($wp_version, '3.4', '<')) {
            // For pre-3.4 support
            $wp_rewrite->extra_permastructs['category'][0] = '%category%';
        } else {
            $wp_rewrite->extra_permastructs['category']['struct'] = '%category%';
        }
    }

    // Add our custom category rewrite rules
    add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
    function no_category_base_rewrite_rules($category_rewrite)
    {
        //var_dump($category_rewrite); // For Debugging

        $category_rewrite = array();
        $categories       = get_categories(array('hide_empty' => false));
        foreach ($categories as $category) {
            $category_nicename = $category->slug;
            if ($category->parent == $category->cat_ID) // recursive recursion
            {
                $category->parent = 0;
            } elseif (0 != $category->parent) {
                $category_nicename = get_category_parents($category->parent, false, '/', true) . $category_nicename;
            }

            $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
            $category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$']                  = 'index.php?category_name=$matches[1]&paged=$matches[2]';
            $category_rewrite['(' . $category_nicename . ')/?$']                                    = 'index.php?category_name=$matches[1]';
        }
        // Redirect support from Old Category Base
        global $wp_rewrite;
        $old_category_base                               = get_option('category_base') ? get_option('category_base') : 'category';
        $old_category_base                               = trim($old_category_base, '/');
        $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';

        //var_dump($category_rewrite); // For Debugging
        return $category_rewrite;
    }
    // Add 'category_redirect' query variable
    add_filter('query_vars', 'no_category_base_query_vars');
    function no_category_base_query_vars($public_query_vars)
    {
        $public_query_vars[] = 'category_redirect';
        return $public_query_vars;
    }

    // Redirect if 'category_redirect' is set
    add_filter('request', 'no_category_base_request');
    function no_category_base_request($query_vars)
    {
        //print_r($query_vars); // For Debugging
        if (isset($query_vars['category_redirect'])) {
            $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
            status_header(301);
            header("Location:$catlink");
            exit();
        }
        return $query_vars;
    }
}


// 上传文件自动重命名
function el_new_filename($file)
{

    if (_opz('newfilename_type') !== 'random') {
        $file['name'] = current_time('YmdHis') . mt_rand(10, 99) . mt_rand(0, 9) . '-' . $file['name'];
    } else {
        $info         = pathinfo($file['name']);
        $ext          = empty($info['extension']) ? '' : '.' . $info['extension'];
        $md5          = md5($file['name']);
        $file['name'] = substr($md5, 0, 10) . current_time('YmdHis') . $ext;
    }

    return $file;
}
if (_opz('newfilename')) {
    add_filter('wp_handle_upload_prefilter', 'el_new_filename', 99);
    add_filter('wp_handle_sideload_prefilter', 'el_new_filename', 99);
}


// 缓存获取附件的月份。
add_filter('media_library_months_with_files', function ($months) {
    $months    = get_transient('el_media_library_months');

    if ($months === false) {
        global $wpdb;

        $months = $wpdb->get_results("SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC");

        set_transient('el_media_library_months', $months, WEEK_IN_SECONDS);
    }

    return $months;
});

// 删除附件月份的缓存
function el_delete_media_library_months_cache()
{
    delete_transient('el_media_library_months');
}
add_action('edit_attachment',    'el_delete_media_library_months_cache');
add_action('add_attachment',    'el_delete_media_library_months_cache');
add_action('delete_attachment',    'el_delete_media_library_months_cache');

// URL防止危险代码
if (
    strpos($_SERVER["REQUEST_URI"], "eval(") || strpos($_SERVER["REQUEST_URI"], "base64") || strpos($_SERVER["REQUEST_URI"], "/**/")
) {
    @header("HTTP/1.1 414 Request-URI Too Long");
    @header("Status: 414 Request-URI Too Long");
    @header("Connection: Close");
    @exit;
}

// 禁止多地同时登录
function pcl_user_has_concurrent_sessions()
{
    return (is_user_logged_in() && count(wp_get_all_sessions()) > 2);
}
add_action("init", function () {
    // 除了管理员，其他人不允许多地同时登陆。
    if (!current_user_can("manage_options")) {
        if (!pcl_user_has_concurrent_sessions()) {
            return;
        }
        $newest = max(wp_list_pluck(wp_get_all_sessions(), "login"));
        $session = pcl_get_current_session();
        if ($session["login"] === $newest) {
            wp_destroy_other_sessions();
        } else {
            wp_destroy_current_session();
        }
    }
});

add_filter("admin_footer_text", function () {
    return '感谢您使用强大的 <a href="https://wordpress.org">WordPress</a> 搭配 <a href="" target="_blank">Eleven自媒体主题</a> 使用';
});


//在后台文章列表增加一列数据
add_filter('manage_posts_columns', 'customer_posts_columns');
function customer_posts_columns($columns)
{
    $columns['views'] = '浏览次数';
    return $columns;
}

//输出浏览次数
add_action('manage_posts_custom_column', 'customer_columns_value', 10, 2);
function customer_columns_value($column, $post_id)
{
    if ($column == 'views') {
        $count = ECache::get($post_id,'post_views_'.$post_id);
        // $count = get_post_meta($post_id, 'views', true);
        if(false === $count){
            $count = get_post_meta($post_id, 'views', true);
            if (!$count) {
                $count = 0;
            }
            ECache::set($post_id,'post_views_'.$post_id,43200);
        }
        echo $count;
    }
    return;
}